package netty.udp.demo4;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.kqueue.KQueue;
import io.netty.channel.kqueue.KQueueChannelOption;
import io.netty.channel.kqueue.KQueueDatagramChannel;
import io.netty.channel.kqueue.KQueueEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * @program netty-demo
 * @description:
 * @author: zhanglu
 * @create: 2020-07-01 10:48:00
 */
public class UdpClient {

    public static final int MessageReceived = 0x99;
    private static int scanPort = 2555;

    public UdpClient(int scanPort) {
        this.scanPort = scanPort;
    }


    private static class CLientHandler extends SimpleChannelInboundHandler<DatagramPacket> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
            String body = packet.content().toString(CharsetUtil.UTF_8);
            System.out.println(body);
        }
    }

    public static void main(String[] args) {
        int cpuNum = Runtime.getRuntime().availableProcessors();
        KQueueEventLoopGroup group = new KQueueEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(KQueueDatagramChannel.class)
                    .handler(new CLientHandler());
            // linux平台下支持SO_REUSEPORT特性以提高性能
            if (KQueue.isAvailable()) {
                b.option(KQueueChannelOption.SO_REUSEPORT, true);
            }
            Channel ch = b.bind(8401).sync().channel();

            ch.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer("我们平台给7408发送消息", CharsetUtil.UTF_8),
                    new InetSocketAddress("127.0.0.1", 7408))).sync();

            ch.closeFuture().await();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }


}
